package com.xiliubit.cloudpicture.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.mapper.SpaceMapper;
import com.xiliubit.cloudpicture.model.dto.space.SpaceAddRequest;
import com.xiliubit.cloudpicture.model.dto.space.SpaceQueryRequest;
import com.xiliubit.cloudpicture.model.dto.user.UserQueryRequest;
import com.xiliubit.cloudpicture.model.entity.Space;
import com.xiliubit.cloudpicture.model.entity.SpaceUser;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.SpaceLevelEnum;
import com.xiliubit.cloudpicture.model.enums.SpaceRoleEnum;
import com.xiliubit.cloudpicture.model.enums.SpaceTypeEnum;
import com.xiliubit.cloudpicture.model.vo.SpaceVO;
import com.xiliubit.cloudpicture.model.vo.UserInfoVO;
import com.xiliubit.cloudpicture.service.SpaceService;
import com.xiliubit.cloudpicture.service.SpaceUserService;
import com.xiliubit.cloudpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
* @author 86173
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-08-08 14:17:41
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    private UserService userService;

    @Resource
    private SpaceUserService spaceUserService;

    @Resource
    private TransactionTemplate transactionTemplate;

    // 本地锁优化
    Map<Long, Object> lockMap = new ConcurrentHashMap<>();

    @Override
    public SpaceVO getSpaceVO(Space space, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        SpaceVO spaceVO = SpaceVO.objToVo(space);
        spaceVO.setUser(userService.getUserInfo(loginUser));
        return spaceVO;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper <Space> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null){
            return queryWrapper;
        }

        Long id = spaceQueryRequest.getId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Long userId = spaceQueryRequest.getUserId();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        Integer spaceType = spaceQueryRequest.getSpaceType();

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel), "spaceLevel", spaceLevel);
        queryWrapper.like(StrUtil.isNotBlank(spaceName), "spaceName", spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceType), "spaceType", spaceType);

        // 排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField),sortOrder.equals(UserQueryRequest.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public Page<SpaceVO> getSpaceVOPage(Page<Space> page, HttpServletRequest request) {

        List<Space> spaceList = page.getRecords();
        Page<SpaceVO> spaceVOPage = new Page<>(page.getCurrent(), page.getSize(),page.getTotal());
        if (spaceList.isEmpty()){
            return spaceVOPage;
        }
        // 封装到VO
        List<SpaceVO> pictureVOList = spaceList.stream()
                .map(SpaceVO::objToVo)
                .collect(Collectors.toList());

        // 获取用户信息
        Set<Long> userIdList = spaceList.stream()
                .map(Space::getUserId)
                .collect(Collectors.toSet());
        List<User> userList = userService.listByIds(userIdList);
        List<UserInfoVO> userVOList = userService.getUserVOList(userList);
        Map<Long, UserInfoVO> userInfoVOMap = userVOList.stream()
                .collect(Collectors.toMap(UserInfoVO::getId, userVO -> userVO));

        // 为每个pictureVO设置userInfoVO
        pictureVOList.forEach(pictureVO -> {
            if (userInfoVOMap.containsKey(pictureVO.getUserId())){
                pictureVO.setUser(userInfoVOMap.get(pictureVO.getUserId()));
            }
        });

        spaceVOPage.setRecords(pictureVOList);
        return spaceVOPage;
    }

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(spaceLevel);
        Integer spaceType = space.getSpaceType();
        SpaceTypeEnum spaceTypeEnum = SpaceTypeEnum.getEnumByValue(spaceType);
        // 要创建
        if (add) {
            if (StrUtil.isBlank(spaceName)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称不能为空");
            }
            if (spaceLevel == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不能为空");
            }
            if (spaceType == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不能为空");
            }
        }
        // 修改数据时，如果要改空间级别
        if (spaceLevel != null && spaceLevelEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间级别不存在");
        }
        if (StrUtil.isNotBlank(spaceName) && spaceName.length() > 30) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间名称过长");
        }
        //为了健壮性 -- 修改数据时，如果要改空间级别（虽然在业务逻辑里用不到）
        if (spaceType != null && spaceTypeEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间类型不存在");
        }
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        // 根据空间级别，自动填充限额
        SpaceLevelEnum spaceLevelEnum = SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if (spaceLevelEnum != null) {
            long maxSize = spaceLevelEnum.getMaxSize();
            if (space.getMaxSize() == null) {
                space.setMaxSize(maxSize);
            }
            long maxCount = spaceLevelEnum.getMaxCount();
            if (space.getMaxCount() == null) {
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser){
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        // 默认值
        if (StrUtil.isBlank(spaceAddRequest.getSpaceName())) {
            space.setSpaceName("默认空间");
        }
        if (spaceAddRequest.getSpaceLevel() == null) {
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        if (spaceAddRequest.getSpaceType() == null) {
            spaceAddRequest.setSpaceType(SpaceTypeEnum.PRIVATE.getValue());
        }
        // 填充数据
        this.fillSpaceBySpaceLevel(space);
        Long userId = loginUser.getId();
        space.setUserId(userId);
        // 参数校验
        this.validSpace(space, true);
        // 2. 校验权限(非管理员只能创建普通的空间)
        if (SpaceLevelEnum.COMMON.getValue() != space.getSpaceLevel() && !userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限创建指定级别的空间");
        }
        // 3. 控制同一个用户只能创建一个空间（给创建加锁）
        Object lock = lockMap.computeIfAbsent(userId, key -> new Object());
        synchronized (lock){
            try {
                Long newSpaceId = transactionTemplate.execute(status -> {
                    // 判断用户是否已经创建过空间
                    boolean exists = this.lambdaQuery()
                            .eq(Space::getUserId, userId)
                            .eq(Space::getSpaceType, space.getSpaceType())
                            .exists();
                    ThrowUtils.throwIf(exists, ErrorCode.OPERATION_ERROR, "不同空间用户只能创建一个");
                    // 写入数据库
                    boolean result = this.save(space);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
                    // 如果是团队空间，关联新增团队成员记录
                    if (SpaceTypeEnum.TEAM.getValue() == spaceAddRequest.getSpaceType()) {
                        SpaceUser spaceUser = new SpaceUser();
                        spaceUser.setSpaceId(space.getId());
                        spaceUser.setUserId(userId);
                        spaceUser.setSpaceRole(SpaceRoleEnum.ADMIN.getValue());
                        result = spaceUserService.save(spaceUser);
                        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "创建团队成员记录失败");
                    }
                    // 返回新写入的数据 id
                    return space.getId();
                });
                // 返回包装类Long
                return newSpaceId;
            }finally {
                // 移除锁
                // 防止内存泄漏
                lockMap.remove(userId);
            }
        }
    }

    /**
     * 校验用户对空间是否有权限
     * @param loginUser
     * @param space
     */
    @Override
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅允许管理员和创建者访问
        if (!loginUser.getId().equals(space.getUserId()) && !userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无空间权限");
        }
    }
}




